package com.hn658.base.message.notisender.sender.comet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;

import com.hn658.framework.common.AbstractBusinessObject;
import com.hn658.framework.logging.enums.LogCategory;

public class CometAsyncListener extends AbstractBusinessObject implements AsyncListener {
	
	private String userId;
	
	private String appKey;
	
	private IIsOnlineManager isOnlineManager;
	
	public CometAsyncListener(String appKey,String userId,IIsOnlineManager isOnlineManager){
		this.userId = userId;
		this.appKey = appKey;
		this.isOnlineManager = isOnlineManager;
	}

	@Override
    public void onComplete(AsyncEvent asyncEvent) throws IOException {
        logger.debug(LogCategory.SYSTEM, "长链接userId :"+userId+" 已结束.");
    }

    @Override
    public void onTimeout(AsyncEvent asyncEvent) throws IOException {
    	String appUid=userId+"_"+appKey;
    	AsyncContext asyncContext = AsyncContextCache.get(appUid);
        logger.debug(LogCategory.SYSTEM, "长链接 userId :"+userId+"   appKey :"+appKey+" 超时,发送心跳包检查其是否仍在线.");
        PrintWriter out = asyncContext.getResponse().getWriter();
        synchronized (asyncContext) {
			out.print("|------|");
			out.flush();
        }
        if (out.checkError()) {
            logger.debug(LogCategory.SYSTEM, "长链接  userId :"+userId+"   appKey :"+appKey+" 心跳包发送出错，将其结束.");
            AsyncContextCache.remove(appUid);
            isOnlineManager.offline(appKey, userId);
            asyncContext.complete();
        } else {
            logger.debug(LogCategory.SYSTEM, "长链接 userId :"+userId+"   appKey :"+appKey+" 心跳成功.");
            isOnlineManager.online(appKey, userId);
        }
    }

    @Override
    public void onError(AsyncEvent asyncEvent) throws IOException {
    	String appUid=userId+"_"+appKey;
    	AsyncContext asyncContext = AsyncContextCache.get(appUid);
        logger.debug(LogCategory.SYSTEM, "处理长链接 userId :"+userId+"   appKey :"+appKey+" 出错,将其结束.");
        AsyncContextCache.remove(appUid);
        isOnlineManager.offline(appKey, userId);
        asyncContext.complete();
    }

    @Override
    public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
    	logger.debug(LogCategory.SYSTEM, "长链接 userId :"+userId+"   appKey :"+appKey+" 已开始.");
    }

}
